/******************************************************************
 *
 *    Java Lib For JavaWeb, Powered By Shenzhen WEI YI KE JI .
 *
 *    Copyright (c) 2017-2027 Digital Telemedia Co.,Ltd
 *    http://www.d-telemedia.com/
 *
 *    Package:     com.theyeasy.dvmini.service.impl
 *
 *    Filename:    ProjectServiceImpl.java
 *
 *    Description: TODO(用一句话描述该文件做什么)
 *
 *    Copyright:   Copyright (c) 2017-2027
 *
 *    Company:     Theyeasy Telemedia Co.,Ltd
 *
 *    @author:     hm
 *
 *    @version:    1.0.0
 *
 *    Create at:   2017年10月22日 下午5:53:36
 *
 *    Revision:
 *
 *    2017年10月22日 下午5:53:36
 *        - first revision
 *
 *****************************************************************/
package com.theyeasy.dvmini.service.impl;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.lang3.RandomUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.testng.util.Strings;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.theyeasy.dvmini.dao.AutoreplyDao;
import com.theyeasy.dvmini.dao.PostertempletDao;
import com.theyeasy.dvmini.model.Autoreply;
import com.theyeasy.dvmini.model.Postertemplet;
import com.theyeasy.dvmini.model.Projects;
import com.theyeasy.dvmini.service.AutoreplyService;
import com.theyeasy.dvmini.service.DvminiSocketService;
import com.theyeasy.dvmini.util.CommonUtil;
import com.theyeasy.dvmini.util.KeywordUtil;
import com.theyeasy.dvmini.util.PageResults;
import com.theyeasy.dvmini.util.StringUtil;
import com.theyeasy.dvmini.util.keyword.RegexKeywordFilter;
import com.theyeasy.dvmini.util.keyword.ReplaceStrategy;

import tk.mybatis.mapper.entity.Example;

/**
 * @ClassName ProjectServiceImpl
 * @Description TODO(这里用一句话描述这个类的作用)
 * @author hm
 * @Date 2017年10月22日 下午5:53:36
 * @version 1.0.0
 */
@Service
public class AutoreplyServiceImpl implements AutoreplyService {

	Logger log = LoggerFactory.getLogger(AutoreplyService.class);
	@Autowired
	AutoreplyDao autoreplyDao;

	static List<RegexKeywordFilter> filterList = Lists.newArrayList();

	static boolean inited = false;

	public void init() {
		if (inited)
			return;
		List<Autoreply> autoreplyList = autoreplyDao.selectAll();
		autoreplyList.stream().forEach(e -> {
			String[] keys = e.getKeywords().split("\\|");
			RegexKeywordFilter filter = new RegexKeywordFilter();
			for (String key : keys) {
				filter.add(key);
			}
			filter.compile();
			filterList.add(filter);
		});
		inited = true;
	}

	@Override
	public PageResults<Autoreply> getAutoReplyList(Integer page, String keyword, Boolean isRedirectStaff) {
		Example example = new Example(Autoreply.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("deleted", false);

		if (!Strings.isNullOrEmpty(keyword)) {
			criteria.andLike("contents", "%" + keyword + "%");
			example.or().andLike("keywords", "%" + keyword + "%");

		}

		if (isRedirectStaff != null) {
			criteria.andEqualTo("isredirectstaff", isRedirectStaff);
		}
		RowBounds row = new RowBounds((page - 1) * 10, 10);
		example.setOrderByClause(" id desc ");
		List<Autoreply> list = autoreplyDao.selectByExampleAndRowBounds(example, row);
		int total = autoreplyDao.selectCountByExample(example);
		PageResults<Autoreply> pageresult = new PageResults<>();
		pageresult.setPage(page);
		pageresult.setPageSize(10);
		pageresult.setRows(list);
		pageresult.setTotal(total);
		return pageresult;
	}

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see
	 * com.theyeasy.dvmini.service.AutoreplyService#addAutoReply(java.lang.String,
	 * boolean, java.lang.String)
	 */
	@Override
	public String addAutoReply(String keywords, boolean isRedirectStaff, String content) {
		if (Strings.isNullOrEmpty(keywords))
			return "关键字设置不能为空";
		int row = 0;
		try {
			Autoreply reply = new Autoreply();
			reply.setContents(content);
			reply.setKeywords(keywords);
			reply.setDeleted(false);
			reply.setIsredirectstaff(isRedirectStaff);
			reply.setUpdatedtime(CommonUtil.getTime());
			row = autoreplyDao.insertSelective(reply);

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("error:" + e.getMessage());
		}
		return row > 0 ? "ok" : "添加失败，数据异常";
	}

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see com.theyeasy.dvmini.service.AutoreplyService#updateAutoReply(java.lang.
	 * Integer, java.lang.String, boolean, java.lang.String)
	 */
	@Override
	public String updateAutoReply(Integer id, String keywords, boolean isRedirectStaff, String content) {
		if (StringUtil.isZearoOrNull(id))
			return "id 不能为空";
		if (Strings.isNullOrEmpty(keywords))
			return "关键字设置不能为空";
		Autoreply reply = autoreplyDao.selectByPrimaryKey(id);
		if (reply == null)
			return "修改失败，数据为空";
		reply.setContents(content);
		reply.setKeywords(keywords);
		reply.setIsredirectstaff(isRedirectStaff);
		reply.setUpdatedtime(CommonUtil.getTime());
		int row = autoreplyDao.updateByPrimaryKeySelective(reply);
		return row > 0 ? "ok" : "修改失败，数据异常";
	}

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see
	 * com.theyeasy.dvmini.service.AutoreplyService#deleteProject(java.lang.Integer)
	 */
	@Override
	public String deleteAutoReply(Integer id) {
		if (StringUtil.isZearoOrNull(id))
			return "id 不能为空";
		Autoreply reply = autoreplyDao.selectByPrimaryKey(id);
		if (reply == null)
			return "删除失败，数据为空";
		reply.setDeleted(true);
		int row = autoreplyDao.updateByPrimaryKeySelective(reply);
		return row > 0 ? "ok" : "删除失败，数据异常";
	}

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see
	 * com.theyeasy.dvmini.service.AutoreplyService#getProject(java.lang.Integer)
	 */
	@Override
	public Autoreply getAutoReply(Integer id) {
		if (StringUtil.isZearoOrNull(id))
			return null;
		return autoreplyDao.selectByPrimaryKey(id);
	}

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see com.theyeasy.dvmini.service.AutoreplyService#KeywordsToString()
	 */
	@Override
	public String KeywordsToString() {
		Example example = new Example(Autoreply.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("deleted", false);
		List<Autoreply> list = autoreplyDao.selectByExample(example);

		// String
		// regex="(?<no1>[23|2莞|2]+)|(?<no2>[买房|东莞|万科]+)|(?<no3>[a|b|cc]+)|(?<no4>[客服|房价|咨询]+)";
		String result = "";
		StringBuffer sb = new StringBuffer();
		if (list != null && list.size() > 0) {
			// List<String> keywordsStr=list.stream().map(e -> new String(
			// (e.getKeywords() == null ? "" :
			// e.getKeywords()+"|"))).collect(Collectors.toList());
			for (Autoreply auto : list) {
				String group = "(?<no_" + auto.getId() + ">[" + auto.getKeywords() + "])" + ",";
				sb.append(group);
			}
			result = sb.toString().replaceAll(",|，", "|");
			if (result.endsWith("|")) {
				result = result.substring(0, result.length() - 1);
			}
			System.out.println(result);

		}
		KeywordUtil.setKeywordStr(result);
		return result;
	}

	@Override
	public Autoreply autoreply(String string) {
		List<Set> sets = Lists.newArrayList();

		for (RegexKeywordFilter filter : filterList) {
			Set<String> keys = Sets.newHashSet();
			filter.replace(string, new ReplaceStrategy() {
				@Override
				public String replaceWith(String keyword) {
					keys.add(keyword);
					sets.add(keys);
					return "";
				}
			});
		}

		Collections.sort(sets, new Comparator<Set>() {
			@Override
			public int compare(Set o1, Set o2) {
				if (o1.size() > o2.size()) {
					return -1;
				}
				if (o1.size() == o2.size()) {
					return 0;
				}
				return 1;
			}
		});
		if (sets.isEmpty())
			return null;
		List<String> list = Lists.newArrayList();
		list.addAll(sets.get(0));
		 List<Autoreply> autoreplys = autoreplyDao.findByKeys(list);
	        if (autoreplys.isEmpty()) return null;
	       Integer index  = RandomUtils.nextInt(0,autoreplys.size());
	        log.info("Index:{}, Q:{},A:{}",index,string,autoreplys.get(index).getContents());
	        return autoreplys.get(index);
	}
}
